package com.login.framework.core;

import java.util.Map;

import com.asynccommand.framework.BaseCommand;
import com.login.framework.LoginFramework;
import com.login.framework.model.User;
import com.login.framework.utils.BlackListManager;
import com.login.framework.utils.LogManager;

public abstract class BaseLoginCommand extends BaseCommand {

	private int failedIntents = 0;

	protected String username;
	protected String password;

	/**
	 * Debe implementarse para devolver el usuario logueado correctamente.
	 * 
	 * @return
	 */
	public abstract User getLoggedUser();

	/**
	 * Debe implementarse para ejecutar la tarea necesaria para loguear el
	 * usuario
	 * 
	 * @param resultSet
	 * @return
	 */
	protected abstract Map<String, Object> processLoginResult(
			Map<String, Object> resultSet);

	@Override
	protected void setup(Map<String, Object> params) {
		username = (String) params.get(LoginActionParamsCodes.PARAM_USERNAME);
		password = (String) params.get(LoginActionParamsCodes.PARAM_PASSWORD);
	}

	@Override
	protected final Map<String, Object> processResult(
			Map<String, Object> resultSet) {

		if (LoginFramework.get().getConfig().blackListEnabled()
				&& BlackListManager.get().isUserBlackListed(username)) {

			resultSet.put(RESULT_CODE, ERROR);
			resultSet.put(ERROR_MSG, "User is blacklisted");

		} else {

			resultSet = processLoginResult(resultSet);

			if (!resultSet.get(RESULT_CODE).equals(OK)) {

				failedIntents++;
				if (failedIntents == 3
						&& LoginFramework.get().getConfig().blackListEnabled()) {
					BlackListManager.get().addUser(username);
				}

			}
		}

		if (LoginFramework.get().getConfig().logEnabled()) {
			LogManager.get().log(username,
					resultSet.get(RESULT_CODE).equals(OK));
		}

		return resultSet;
	}
}
